package com.lebang.lechuangsystem.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.lebang.lechuangsystem.common.SessionUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义拦截器
 * 对用户登陆状态校验
 *
 * @author hwq
 */
@Component
public class BaseInterceptor implements HandlerInterceptor {


    /**
     * 该方法将在请求处理之前进行调用，只有该方法返回true，才会继续执行后续的Interceptor和Controller，
     * 当返回值为true 时就会继续调用下一个Interceptor的preHandle 方法，
     * 如果已经是最后一个Interceptor的时候就会是调用当前请求的Controller方法
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {

        Integer user= SessionUtil.getSessionId();
        if(user==null){
            responseMsg(response,"600","会话过期请重新登录");
            return true;
        }
        String uri = request.getRequestURI();
        System.out.println(uri);
        if(uri.startsWith("swagger")){
            return true;
        }
        // 从 http 请求头中取出 token
        return true;
    }


    private void responseMsg(HttpServletResponse response, String status, String msg) throws IOException {
        JsonData jsonData = Callback.fail(status, msg, "");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        String json = JSONObject.toJSONString(jsonData);
        PrintWriter out = response.getWriter();
        out.print(json);
        out.flush();
        out.close();
    }


    /**
     * 该方法将在请求处理之后，DispatcherServlet进行视图返回渲染之前进行调用，可以在这个方法中对Controller 处理之后的ModelAndView 对象进行操作
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 该方法也是需要当前对应的Interceptor的preHandle方法的返回值为true时才会执行，该方法将在整个请求结束之后，也就是在DispatcherServlet 渲染了对应的视图之后执行。用于进行资源清理
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
